package com.cheyun.netsalev3.repository

import android.os.Looper
import android.widget.Toast
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.api.ApiClient
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Response
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import kotlin.reflect.KFunction1

class HomeAnalysisFragmentRepository {
    var uid = 0
    //本月第一天
    var stime = ""
    //当前时间
    var etime = ""

    init {
        MySharedPreferences.getLoginData()?.member?.uid?.apply {
            uid = this
        }
        var dateFormat = SimpleDateFormat("yyyy-MM-dd")
        val c = Calendar.getInstance()
        etime = dateFormat.format(c.timeInMillis)
        c.add(Calendar.MONTH, 0)
        c.set(Calendar.DAY_OF_MONTH, 1)//设置为1号,当前日期既为本月第一天
        stime = dateFormat.format(c.timeInMillis)

    }

    fun getData(
            datetype: String,
            infotype: String,
            kFunction1: KFunction1<@ParameterName(name = "p") JSONObject, Unit>) {
        //datetype   时间类型  day 按天展开  month  按月展开
        var temsime = if (datetype == "day") etime else stime
        var call = ApiClient.getInstance().getAnalysisToPer(temsime, uid, etime, datetype, infotype)
        call.enqueue(
                object : retrofit2.Callback<ResponseBody> {
                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {

                    }

                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        response.body()?.string()?.apply {
                            try {
                                var json = JSONObject(this)
                                var state = json.optString("state")
                                var msg = json.optString("msg")
                                var data = json.optJSONObject("data")
                                if (state == "y") {
                                    data?.apply(kFunction1)
                                } else {
                                    Looper.prepare()
                                    Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG).show()
                                    Looper.loop()

                                }
                            } catch (e: Exception) {

                            }

                        }

                    }
                })


    }

}